<template>
  <view class="rich-text-container" :style="containerStyle">
    <rich-text :nodes="parsedHtml"></rich-text>
  </view>
</template>

<script>
export default {
  name: 'RichTextBlock',
  props: {
    blockData: {
      type: Object,
      default: () => ({})
    }
  },
  
  data() {
    return {
      parsedHtml: '',
      containerStyle: ''
    }
  },
  
  mounted() {
    this.parseContent()
  },
  
  watch: {
    blockData: {
      handler() {
        this.parseContent()
      },
      deep: true
    }
  },
  
  methods: {
    /**
     * 解析内容并生成HTML
     */
    parseContent() {
      if (!this.blockData || !this.blockData.content) {
        return
      }
      
      const { content, style } = this.blockData
      const parsedHtml = this.parseMarkdown(content.text || '')
      const containerStyle = this.generateContainerStyle(content, style)
      
      this.parsedHtml = parsedHtml
      this.containerStyle = containerStyle
    },
    
    /**
     * Markdown解析核心函数
     * @param {string} text - 原始文本内容
     * @returns {string} 解析后的HTML字符串
     */
    parseMarkdown(text) {
      if (!text) return ''
      
      const codeBlocks = []
      const inlineCodes = []
      
      // 1. 提取代码块
      text = text.replace(/(```|~~~)([\s\S]*?)\1/g, (match, delimiter, code) => {
        const placeholder = `__CODE_BLOCK_${codeBlocks.length}__`
        const codeBlockHtml = `
          <div style="background: #121212; border-radius: 5px; margin: 12px 0;">
            <div style="background: #121212; padding: 10px; display: flex;">
              <div style="width: 10px; height: 10px; border-radius: 5px; background: #E0443E; margin-left: 10px;"></div>
              <div style="width: 10px; height: 10px; border-radius: 5px; background: #DEA123; margin-left: 5px;"></div>
              <div style="width: 10px; height: 10px; border-radius: 5px; background: #1AAB29; margin-left: 5px;"></div>
            </div>
            <pre style="background: #121212; padding: 16px; color: #ffffff; font-family: monospace; margin: 0; white-space: pre-wrap;">${code.trim()}</pre>
          </div>`
        codeBlocks.push(codeBlockHtml)
        return placeholder
      })
      
      // 2. 提取行内代码
      text = text.replace(/`([^`]+)`/g, (match, code) => {
        const placeholder = `__INLINE_CODE_${inlineCodes.length}__`
        const inlineCodeHtml = `<code style="background: #f1f5f9; padding: 2px 4px; border-radius: 3px; font-family: monospace; color: #e11d48;">${code}</code>`
        inlineCodes.push(inlineCodeHtml)
        return placeholder
      })
      
      // 3. 处理引用块
      text = text.replace(/(^>\s*.+$\n?)+/gm, (match) => {
        const lines = match.split('\n').filter(line => line.trim())
        const content = lines.map(line => line.replace(/^>\s*/, '')).join('<br>')
        return `<blockquote style="margin: 8px 0; padding: 8px 16px; border-left: 4px solid #3b82f6; background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%); color: #000000; border-radius: 8px;">${content}</blockquote>`
      })
      
      // 4. 处理表格
      text = text.replace(/\|(.+)\|\n\|([\s\S]*?)\|\n((?:\|.+\|\n?)*)/g, (match, header, separator, rows) => {
        const headerCells = header.split('|').map(cell => cell.trim()).filter(cell => cell)
        const headerRow = '<tr>' + headerCells.map(cell => `<th style="padding: 8px; border: 1px solid #ddd; background: #f8f9fa;">${cell}</th>`).join('') + '</tr>'
        
        const tableRows = rows.trim().split('\n').map(row => {
          const cells = row.replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim())
          return '<tr>' + cells.map(cell => `<td style="padding: 8px; border: 1px solid #ddd;">${cell}</td>`).join('') + '</tr>'
        }).join('')
        
        return `<table style="border-collapse: collapse; width: 100%; margin: 12px 0; border: 1px solid #ddd;">${headerRow}${tableRows}</table>`
      })
      
      // 5. 处理有序列表
      text = text.replace(/(^\d+\.\s+.+$\n?)+/gm, (match) => {
        const items = match.trim().split('\n').map(line => {
          const content = line.replace(/^\d+\.\s+/, '')
          return `<li style="margin: 4px 0;">${content}</li>`
        }).join('')
        return `<ol style="margin: 8px 0; padding-left: 20px;">${items}</ol>`
      })
      
      // 6. 处理无序列表
      text = text.replace(/(^[-*+]\s+.+$\n?)+/gm, (match) => {
        const items = match.trim().split('\n').map(line => {
          const content = line.replace(/^[-*+]\s+/, '')
          return `<li style="margin: 4px 0;">${content}</li>`
        }).join('')
        return `<ul style="margin: 8px 0; padding-left: 20px;">${items}</ul>`
      })
      
      // 7. 处理标题
      text = text.replace(/^###\s+(.+)$/gm, '<h3 style="font-size: 18px; font-weight: bold; margin: 16px 0 8px 0; color: #1f2937;">$1</h3>')
      text = text.replace(/^##\s+(.+)$/gm, '<h2 style="font-size: 20px; font-weight: bold; margin: 20px 0 10px 0; color: #1f2937;">$1</h2>')
      text = text.replace(/^#\s+(.+)$/gm, '<h1 style="font-size: 24px; font-weight: bold; margin: 24px 0 12px 0; color: #1f2937;">$1</h1>')
      
      // 8. 处理链接
      text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" style="color: #3b82f6; text-decoration: underline;">$1</a>')
      
      // 9. 处理文本样式
      text = text.replace(/~~([^~]+)~~/g, '<del style="text-decoration: line-through;">$1</del>')
      text = text.replace(/\*\*([^*]+)\*\*/g, '<strong style="font-weight: bold;">$1</strong>')
      text = text.replace(/\*([^*]+)\*/g, '<em style="font-style: italic;">$1</em>')
      
      // 10. 处理换行
      text = text.replace(/\n/g, '<br>')
      
      // 11. 恢复代码块
      codeBlocks.forEach((block, index) => {
        text = text.replace(`__CODE_BLOCK_${index}__`, block)
      })
      
      // 12. 恢复行内代码
      inlineCodes.forEach((code, index) => {
        text = text.replace(`__INLINE_CODE_${index}__`, code)
      })
      
      return text
    },
    
    /**
     * 生成容器样式
     * @param {Object} content - 内容配置
     * @param {Object} style - 样式配置
     * @returns {string} CSS样式字符串
     */
    generateContainerStyle(content, style) {
      const styles = []
      
      // 基础样式
      styles.push('word-wrap: break-word')
      styles.push('line-height: 1.6')
      
      // 文本样式
      if (content.fontSize) {
        styles.push(`font-size: ${content.fontSize}px`)
      }
      
      if (content.color) {
        styles.push(`color: ${content.color}`)
      }
      
      if (content.textAlign) {
        styles.push(`text-align: ${content.textAlign}`)
      }
      
      if (content.bold) {
        styles.push('font-weight: bold')
      }
      
      if (content.italic) {
        styles.push('font-style: italic')
      }
      
      if (content.underline) {
        styles.push('text-decoration: underline')
      }
      
      if (content.lineThrough) {
        styles.push('text-decoration: line-through')
      }
      
      // 容器样式
      if (style) {
        if (style.backgroundColor && style.backgroundColor !== 'transparent') {
          styles.push(`background-color: ${style.backgroundColor}`)
        }
        
        if (style.borderRadius) {
          styles.push(`border-radius: ${style.borderRadius}px`)
        }
        
        if (style.padding) {
          styles.push(`padding: ${style.padding}px`)
        }
        
        if (style.margin) {
          styles.push(`margin: ${style.margin}px`)
        }
        
        if (style.shadow) {
          styles.push('box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1)')
        }
      }
      
      return styles.join('; ')
    }
  }
}
</script>

<style scoped>
.rich-text-container {
  word-wrap: break-word;
  line-height: 1.6;
  overflow: hidden;
}

/* 深度选择器用于样式穿透 - 小程序兼容版本 */
.rich-text-container >>> .rich-text-blockquote {
  margin: 12px 0;
  padding: 16px 20px;
  border-left: 5px solid #3b82f6;
  background-color: #eff6ff;
  border-radius: 8px;
}

.rich-text-container >>> .rich-text-table {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.rich-text-container >>> .rich-text-th,
.rich-text-container >>> .rich-text-td {
  padding: 8px;
  border: 1px solid #ddd;
  text-align: left;
}

.rich-text-container >>> .rich-text-th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.rich-text-container >>> .rich-text-pre {
  background: #121212;
  color: #ffffff;
  padding: 16px;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
}

.rich-text-container >>> .rich-text-code {
  background: #f1f5f9;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  color: #e11d48;
}

.rich-text-container >>> .rich-text-h1,
.rich-text-container >>> .rich-text-h2,
.rich-text-container >>> .rich-text-h3 {
  color: #1f2937;
  font-weight: bold;
}

.rich-text-container >>> .rich-text-ul,
.rich-text-container >>> .rich-text-ol {
  margin: 8px 0;
  padding-left: 20px;
}

.rich-text-container >>> .rich-text-li {
  margin: 4px 0;
}

.rich-text-container >>> .rich-text-link {
  color: #3b82f6;
  text-decoration: underline;
}
</style>